package com.ypaco.ajax.client;
import com.google.gwt.xml.client.*;

public class XmlProcessor {
	
	public Document doc=null;
	
	public XmlProcessor(Document xml)
	{
		doc=xml;
	}
	
	public Node getRootNode(String verify) throws BadXmlException
	{
		Node root=doc.getDocumentElement();
		if (verify!=null)
			if (verify.compareTo(root.getNodeName())!=0)
				throw new BadXmlException("Неверный корневой элемент "+root.getNodeName()+". Ожидается "+verify+".");
		return root;
	}

	public Node getRootNode() throws BadXmlException
	{
		return getRootNode(null);
	}
	
	public boolean hasAttr(Node nd,String aname)
	{
		Node res=null;
		if (nd.hasAttributes())
			res=nd.getAttributes().getNamedItem(aname);
		return (res!=null);
	}
	
	public Node getNeedAttr(Node node,String aname) throws BadXmlException
	{
		Node res=null;
		if (node.hasAttributes())
			res=node.getAttributes().getNamedItem(aname);
		if (res==null)
			throw new BadXmlException("атрибут не найден "+aname);
		return res;
	}
	
	public Node stdCheck() throws BadXmlException
	{
		Node nd=getRootNode("result");
		String atr=getNeedAttr(nd,"r").getNodeValue();
		if (atr.compareTo("0")!=0)
		{
			String descr=getNeedAttr(nd,"d").getNodeValue();
			throw new BadXmlException("ошибка сервера "+atr+" - "+descr);
		}
		return nd;
	}
	
	public Node findChildByName(Node nd,String name)
	{
		Node nx=nd.getFirstChild();
		while(nx!=null)
		{
		  if (nx.getNodeName().compareTo(name)==0)
		    return nx;
		  nx=nx.getNextSibling();
		}
		return null;
	}
	
	public boolean stdCanEdit() throws BadXmlException
	{
	  Node nd=getRootNode();
	  if (hasAttr(nd,"edit"))
	    if (getNeedAttr(nd,"edit").getNodeValue().compareTo("1")==0)
		  return true;
	  return false;
	}
	
	public String nodeText(Node nd)
	{
	  return nd.getFirstChild().getNodeValue();
	}
	
}
